package com.lanyou.esb.cook.proxy.redis.persistent.impl;

import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.exceptions.JedisException;

import com.lanyou.esb.cook.proxy.entity.PfThroughput;
import com.lanyou.esb.cook.proxy.entity.StoreForward;
import com.lanyou.esb.cook.proxy.redis.persistent.base.BasePersistentRedis;
import com.lanyou.esb.cook.proxy.redis.proxy.impl.StoreForwardJedisProxy;
import com.lanyou.esb.cook.proxy.redis.proxy.impl.StoreForwardKeysJedisProxy;

/**
 * 持久化存储转发统计表<br>
 * 描述：
 *
 * @author Davey.wu
 */
public class StoreForwardPersistentRedis extends
		BasePersistentRedis<StoreForward> {
	/** Redis操作代理 **/
	private StoreForwardJedisProxy jedisProxy;
	/** Redis操作代理 **/
	private StoreForwardKeysJedisProxy keysJedisProxy;

	public StoreForwardPersistentRedis() {
		// 每30秒执行一次
		this.setCron("0 0/1 * * * ?");
		this.setName("StoreForwardPersistentRedis");
		this.setGroup("StoreForwardPersistentRedis");
		this.setJobClass(this.getClass());
	}

	@Override
	public void persistent() throws Exception {
		List<StoreForward> list = new ArrayList<>(this.getBatchAmount());
		list.clear();
		List<StoreForward> objects = null;
		List<String> keys = null;
		while (true) {
			try {
				keys = this.keysJedisProxy.spopAsStr(
						this.keysJedisProxy.getKey(),
						this.getBatchReadSize());
				// 没有数据，返回
				if (keys == null || keys.isEmpty()) {
					break;
				}
				// 获取统计数据
				objects = this.jedisProxy.get(keys);
				if (objects == null || objects.isEmpty()) {
					continue;
				}
				list.addAll(objects);
				// 达到批量保存的数目，将数据保存到数据库
				if (list.size() >= this.getBatchAmount()) {
					getService().save(list);
					list.clear();
				}
			} catch (Exception e) {
				e.printStackTrace();
				if (e instanceof JedisException) {
					break;
				}
				// TODO 如果是将字符串转换成对象时出错，继续读后面的数据
				objects = null;
			}
		}
		// 保存剩余的数据
		getService().save(list);
		list.clear();
	}

	public StoreForwardJedisProxy getJedisProxy() {
		return jedisProxy;
	}

	public void setJedisProxy(StoreForwardJedisProxy jedisProxy) {
		this.jedisProxy = jedisProxy;
	}

	public StoreForwardKeysJedisProxy getKeysJedisProxy() {
		return keysJedisProxy;
	}

	public void setKeysJedisProxy(StoreForwardKeysJedisProxy keysJedisProxy) {
		this.keysJedisProxy = keysJedisProxy;
	}

}
